package org.example.volunteerend.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.example.volunteerend.dto.CommentCreateRequest;
import org.example.volunteerend.dto.PageResponse;
import org.example.volunteerend.dto.ProjectLikeRequest;
import org.example.volunteerend.dto.Result;
import org.example.volunteerend.entity.CommunityComment;
import org.example.volunteerend.service.CommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
public class CommunityController {

    private final CommunityService communityService;
    
    @Autowired
    public CommunityController(CommunityService communityService) {
        this.communityService = communityService;
    }

    /**
     * 添加项目评论
     */
    @PostMapping("/comments")
    public Result<Map<String, Object>> addComment(
            @RequestBody CommentCreateRequest request,
            HttpServletRequest httpRequest) {
        
        // 从JWT获取用户ID
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或登录已过期");
        }
        
        try {
            // 添加评论
            Integer commentId = communityService.addComment(request, userId);
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("comment_id", commentId);
            
            return Result.success("评论发布成功", data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("评论发布失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取项目评论列表
     */
    @GetMapping("/projects/{projectId}/comments")
    public Result<Map<String, Object>> getProjectComments(
            @PathVariable Integer projectId,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String sortOrder) {
        
        try {
            // 获取所有评论（包括回复）
            List<CommunityComment> allComments = communityService.getAllProjectComments(
                    projectId, null, null, "create_time", "asc").getRecords();
            
            // 分离根评论和回复，并建立关联关系
            Map<Integer, List<CommunityComment>> repliesMap = new HashMap<>();
            List<CommunityComment> rootComments = new ArrayList<>();
            
            // 首先找出所有根评论和回复，并按照根评论ID组织回复
            for (CommunityComment comment : allComments) {
                if (comment.getParentCommentId() == null) {
                    // 这是根评论
                    rootComments.add(comment);
                } else {
                    // 这是回复
                    Integer parentId = comment.getParentCommentId();
                    if (!repliesMap.containsKey(parentId)) {
                        repliesMap.put(parentId, new ArrayList<>());
                    }
                    repliesMap.get(parentId).add(comment);
                }
            }
            
            // 应用分页
            int start = (page != null && page > 0) ? (page - 1) * (pageSize != null ? pageSize : 10) : 0;
            int size = (pageSize != null && pageSize > 0) ? pageSize : 10;
            int end = Math.min(start + size, rootComments.size());
            
            // 确保不会出现越界
            if (start >= rootComments.size()) {
                start = Math.max(0, rootComments.size() - size);
                end = rootComments.size();
            }
            
            List<CommunityComment> pagedRootComments = 
                (start < end) ? rootComments.subList(start, end) : new ArrayList<>();
            
            // 构建返回数据结构
            List<Map<String, Object>> rows = new ArrayList<>();
            
            for (CommunityComment rootComment : pagedRootComments) {
                Map<String, Object> commentData = new HashMap<>();
                commentData.put("comment_id", rootComment.getCommentId());
                commentData.put("user_id", rootComment.getUserId());
                
                if (rootComment.getUser() != null) {
                    commentData.put("username", rootComment.getUser().getUsername());
                    commentData.put("real_name", rootComment.getUser().getRealName());
                    commentData.put("avatar_url", rootComment.getUser().getAvatarUrl());
                }
                
                commentData.put("content", rootComment.getContent());
                commentData.put("rating", rootComment.getRating());
                commentData.put("create_time", rootComment.getCreateTime());
                commentData.put("parent_comment_id", rootComment.getParentCommentId());
                
                // 处理回复
                List<Map<String, Object>> repliesData = new ArrayList<>();
                List<CommunityComment> replies = repliesMap.getOrDefault(rootComment.getCommentId(), new ArrayList<>());
                
                for (CommunityComment reply : replies) {
                    Map<String, Object> replyData = new HashMap<>();
                    replyData.put("comment_id", reply.getCommentId());
                    replyData.put("user_id", reply.getUserId());
                    
                    if (reply.getUser() != null) {
                        replyData.put("username", reply.getUser().getUsername());
                        replyData.put("avatar_url", reply.getUser().getAvatarUrl());
                    }
                    
                    replyData.put("content", reply.getContent());
                    replyData.put("create_time", reply.getCreateTime());
                    
                    repliesData.add(replyData);
                }
                
                commentData.put("replies", repliesData);
                rows.add(commentData);
            }
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("total", rootComments.size());
            data.put("rows", rows);
            
            return Result.success("success", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取评论失败：" + e.getMessage());
        }
    }
    
    /**
     * 项目点赞/取消点赞
     */
    @PostMapping("/projects/{projectId}/like")
    public Result<Map<String, Object>> likeProject(
            @PathVariable Integer projectId,
            @RequestBody ProjectLikeRequest request) {
        try {
            // 点赞/取消点赞
            Integer likes = communityService.likeProject(projectId, request.getAction());

            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("likes", likes);
            
            String message = "like".equals(request.getAction()) ? "点赞成功" : "取消点赞成功";
            return Result.success(message, data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作失败：" + e.getMessage());
        }
    }
} 